package com.woniu.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
/**
 * 优雅的实现 mybatis多数据源
 * 在新增数据时除了给自己的库保留一份，还需要同步到别人的库
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"com.woniu.dao.master"},
        sqlSessionFactoryRef = "MasterSqlSessionFactory")
public class MasterDataSourceConfig {

    @Bean(name = "MasterDataSource")
    @Qualifier("MasterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource clickHouseDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "MasterSqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("MasterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/master/*.xml"));
        log.info("------------------------------------------MasterDataSource 配置成功");
        return sessionFactoryBean.getObject();
    }




}
